import { observable, action, computed, runInAction, toJS } from 'mobx';
import BaseStore from '../BaseStore';

class Store extends BaseStore {
    @observable result = null;
    @observable host = '';
    @observable token = '';

    isSuccess = false;
    err;

    @computed
    get resultData() {
        return toJS(this.result? this.result.data || [] :[]);
    }

    @action
    destory() {
        this.result = null;
        this.host = null;
        this.token = null;
        this.isSuccess = false;
        this.err = null;
    }

    @action
    async getUploadToken() {
        const res = await this.get('/upload-token', {
            type: 'document',
            max_size: 5
        }, {
                showGlobalLoading: true
            });
        runInAction(() => {
            if (res.code === '0000') {
                this.host = res.data.host;
                this.token = res.data.token;
            }
        });
    }

    @action
    async submit(data) {
        this.isSuccess = false;
        this.err = null;
        if (!data || !data.file_name || !data.url) {
            this.err = '导入失败，请重试';
            return;
        }
        const res = await this.post('/user/batch-import', data, {
            showGlobalLoading: true
        });
        runInAction(() => {
            if (res.code === '0000') {
                this.isSuccess = true;
                this.result = res.data;
            } else {
                this.result = null;
                this.err = res.message || '导入失败，请重试';
            }
        });
    }
}

export default new Store();